/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.admin.mvc.utils;

import cn.seaboot.commons.core.Tokenizer;
import cn.seaboot.commons.exception.SystemError;
import cn.seaboot.commons.lang.P;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;

/**
 * Freemarker 工具类
 * <p>
 * process()函数都是不带缓存的，
 * <p>
 * 如果需要调用缓存，需要构建FreemarkerRender对象
 *
 * <p>
 * 2020-12-21 Mr.css 尝试使用ClassForTemplateLoading；
 * 2022-01-04 Mr.css TemplateLoader与缓存挂钩，为了兼容更多的场景，索性只保留 “字符串模版” 的功能，大幅度降低代码复杂度；
 * 2022-01-25 Mr.css 增加了缓存的设计。
 *
 * @author Mr.css 2017-10-19
 * @since FreeMarker Version2.3.23
 */
public class Freemarker {
    private Freemarker() {
    }

    /**
     * 默认的配置
     */
    private static Configuration config;

    static {
        try {
            // 通用配置，鉴于Freemarker在项目中的重要程度，出现异常直接抛出error，终止项目的执行。
            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            configuration.setEncoding(P.locale(), Charset.defaultCharset().name());
            configuration.setNumberFormat("0.####");
            configuration.setDateFormat(P.DATE_FORMAT_DATE);
            configuration.setTimeFormat(P.DATE_FORMAT_TIME);
            configuration.setDateTimeFormat(P.DATE_FORMAT_DATETIME);
            configuration.setBooleanFormat("true,false");
            configuration.setWhitespaceStripping(true);
            configuration.setClassicCompatible(true);
            configuration.setTemplateLoader(new StringTemplateLoader());
            config = configuration;
        } catch (Exception e) {
            throw new SystemError("FreeMarker config error: ", e);
        }
    }

    /**
     * 可以用于四则运算
     *
     * @param tpl    代码模版
     * @param values 数值
     * @return 结果
     * @throws IOException       -
     * @throws TemplateException -
     */
    public static String compute(@NotNull String tpl, Map<String, Number> values) throws IOException, TemplateException {
        String str = Tokenizer.process(tpl, values);
        return Freemarker.process("${" + str + "}", Collections.emptyMap());
    }

    /**
     * 渲染模版
     *
     * @param tpl    字符串模版
     * @param model  模型，仅限于对象和 Map
     * @param writer 输出对象
     * @throws IOException       -
     * @throws TemplateException -
     */
    public static void process(String tpl, Object model, Writer writer) throws IOException, TemplateException {
        new Template(null, new StringReader(tpl), config).process(model, writer);
    }

    /**
     * 渲染模版
     *
     * @param tpl   字符串模版
     * @param model 模型，仅限于对象和 Map
     * @throws IOException       -
     * @throws TemplateException -
     */
    public static String process(String tpl, Object model) throws IOException, TemplateException {
        StringWriter out = new StringWriter();
        process(tpl, model, out);
        return out.toString();
    }

    //getter/setter ---------------------------------------------------

    public static void setConfiguration(Configuration config) {
        Freemarker.config = config;
    }

    public static Configuration getConfiguration() {
        return Freemarker.config;
    }
}